<template>
  <div class="process-designer-container">
    <div ref="designer" class="process-designer"></div>
    <div ref="propertiesPanel" class="bpmn-properties-panel"></div>
    <div class="button-container">
      <button @click="saveXml">保存XML</button>
      <button @click="saveSvg">保存SVG</button>
      <!-- 添加导入按钮 -->
      <button @click="triggerImport">导入BPMN</button>
      <input type="file" ref="fileInput" @change="onFileChange" accept=".bpmn,.xml" style="display: none" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import BpmnModeler from 'bpmn-js/lib/Modeler';
// import CustomModeler from './modeler/CustomModeler.ts';
import { BpmnPropertiesPanelModule, BpmnPropertiesProviderModule, } from 'bpmn-js-properties-panel'
import { getBblankBpmnXml } from '../utils/stringUtils.ts';

import { useMessage } from 'naive-ui';
const message = useMessage();

const designer = ref<HTMLElement | null>(null);
const propertiesPanel = ref<HTMLElement | null>(null);
const fileInput = ref<HTMLInputElement | null>(null);
let bpmnModelerInstance: any;

onMounted(() => {
  initBpmnModeler();
});

const initBpmnModeler = async () => {
  if (designer.value && propertiesPanel.value) { // 确保 designer 已经挂载
    bpmnModelerInstance = new BpmnModeler({
      container: designer.value,
      additionalModules: [
        BpmnPropertiesPanelModule,
        BpmnPropertiesProviderModule
      ],
      propertiesPanel: {
        parent: propertiesPanel.value // 确保选择器正确
      }
    });

    // 提供一个有效的 BPMN XML 以确保有内容可以显示
    await bpmnModelerInstance.importXML(getBblankBpmnXml());
  } else {
    console.error('编辑器元素未找到')
  }
};

/**
 * 保存 XML
 */
const saveXml = async () => {
  const { xml } = await bpmnModelerInstance.saveXML({ format: true })
  console.log('导出结果:', xml);
  // 创建并触发下载
  const blob = new Blob([xml], { type: 'application/xml;charset=UTF-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'diagram.bpmn';
  document.body.appendChild(a);
  a.click();

  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  message.success('导出成功');
};

/**
 * 保存 SVG
 */
const saveSvg = async () => {
  const { svg } = await bpmnModelerInstance.saveSVG({ format: true })
  const blob = new Blob([svg], { type: 'image/svg+xml;charset=UTF-8' });
  const url = URL.createObjectURL(blob);

  // 创建下载链接
  const a = document.createElement('a');
  a.href = url;
  a.download = 'diagram.svg';
  document.body.appendChild(a);
  a.click();

  // 清理
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const triggerImport = () => {
  fileInput.value?.click();
};

const onFileChange = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (!file) return;

  try {
    const reader = new FileReader();
    reader.onload = async (e) => {
      const xml = e.target?.result as string;
      try {
        await bpmnModelerInstance.importXML(xml);
      } catch (err) {
        console.error('导入失败:', err);
      }
    };
    reader.readAsText(file);
  } catch (error) {
    console.error('文件读取失败:', error);
  }
  // 清空input，确保能重复选择相同文件
  (event.target as HTMLInputElement).value = '';
};

</script>

<style scoped lang="scss">
@use './ProcessDesigner.scss';
</style>